package com.qd.marketlist;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MyFragment extends Fragment {
    private static final String TAG = "MyFragment";
    private static final boolean DBG = MLConst.DEBUG;
    private static final int DEL_ITEM = 0;
    //private DBHelper mDBHelper;
    //private SQLiteDatabase mSQLDB;
    private MyAdapter mAdapter;
    private Context mContext;
    private Cursor mCur;
    private String mMyType;
    private ProgressBar mPB;
    private TextView mTV;
    private ListView mLv;
    private ListObserver mOb;
    private Uri mUri;
    private Uri mHistoryUri;

    private DialogInterface.OnClickListener addOKInterface =  new DialogInterface.OnClickListener(){
        public void onClick(DialogInterface dialog, int which){
            Cursor cCur = mContext.getContentResolver().query(
                    mUri, null, null,null, null);
            if(DBG) Log.e(TAG,"count" + cCur.getCount());
            cCur.moveToFirst();
            while(!cCur.isAfterLast()){
                String curName = cCur.getString(cCur.getColumnIndex(MLConst.DBSTR_COL_NAME));
                ContentValues values = new ContentValues();

                Cursor c = mContext.getContentResolver().query(
                        mHistoryUri, null,
                        MLConst.DBSTR_COL_NAME + "=?",
                        new String[]{curName}, null);
                c.moveToLast();
                if(0 != c.getCount()){
                    values.put(MLConst.DBSTR_COL_COUNT,
                            c.getInt(c.getColumnIndex(MLConst.DBSTR_COL_COUNT))+1);
                    Long id = c.getLong(c.getColumnIndex(MLConst.DBSTR_COL_ID));
                    mContext.getContentResolver().update(
                            mHistoryUri,
                            values,
                            MLConst.DBSTR_COL_ID + "=" + id.toString() ,
                            null);
                }else{
                    values.put(MLConst.DBSTR_COL_NAME, curName);
                    values.put(MLConst.DBSTR_COL_COUNT,1);

                    mContext.getContentResolver().insert(mHistoryUri, values);
                }
                c.close();
                cCur.moveToNext();
            };
            cCur.close();
            
            mContext.getContentResolver().delete(
                    mUri, null, null);
        }
    };

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg){
            switch(msg.what){
            case MLConst.MSG_CHECKSTATE:{
                refreshProgressBar();
                break;
            }
            case MLConst.MSG_ITEM:{
                notifyDataChanged();
                break;
            }
            default:{
                if(DBG) Log.e(TAG, "unknow msg what");
                break;
            }
            }
        }
    };
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMyType = ((MainActivity)getActivity()).getCurrentTab();
        if(mMyType.equals(MLConst.DBSTR_TYPE_SUPERMARKET)){
            mUri = MyProvider.CONTENT_URI;
            mHistoryUri = MyProvider.CONTENT_HISTORYURI;
        }else{
            mUri = MyProvider.CONTENT_DRUG_URI;
            mHistoryUri = MyProvider.CONTENT_DRUGHISTORY_URI;
        }

        mCur = mContext.getContentResolver().query(
                mUri, null, null, null, null);
           //mDBHelper = new DBHelper(mContext);
           //mSQLDB = mDBHelper.getReadableDatabase();

           //mCur = mSQLDB.query(MLConst.DB_TABLE_NAME,
           //             null,
           //             MLConst.DBSTR_COL_TYPE + "=?",
           //             new String[]{mMyType},
           //             null, null, null, null);

       mCur.moveToLast();
       mAdapter = new MyAdapter(
                    mContext,
                    R.layout.list_item,
                    mCur,
                    new String[]{MLConst.DBSTR_COL_NAME},
                    new int[]{R.id.lv_Title}
                    );
       mAdapter.setUri(mUri);
       mOb = new ListObserver(mContext,mHandler);
       mContext.getContentResolver().registerContentObserver(mUri, true, mOb);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mContext = activity;
    }

    @Override
    public void onResume(){
        super.onResume();
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mCur.close();
        mContext.getContentResolver().unregisterContentObserver(mOb);
    }

    private void refreshProgressBar(){
        int i_max = mCur.getCount();
        
        mPB.setMax(i_max);
        //Cursor c = mSQLDB.query(MLConst.DB_TABLE_NAME,
        //        null,
        //        MLConst.DBSTR_COL_TYPE + "=? and " + MLConst.DBSTR_COL_CHECKBOX_STATE +"=?",
        //        new String[]{mMyType, Integer.toString(MLConst.DB_STATE_CHECKED)},
        //        null, null, null, null);
        Cursor c = mContext.getContentResolver().query(
                mUri,
                null,
                MLConst.DBSTR_COL_CHECKBOX_STATE +"=?",
                new String[]{Integer.toString(MLConst.DB_STATE_CHECKED)}, null);
        int i_progress = c.getCount();
        c.close();
        mPB.setProgress(i_progress);
        mTV.setText(Integer.toString(i_progress)
                + "/"
                + Integer.toString(i_max)
                + " ");
        
        if(0 != i_max && i_max == i_progress){
            if(DBG) Log.e(TAG, "AlertDialog() " + i_progress + "/" + i_max);
            new AlertDialog.Builder(mContext)
            .setTitle(R.string.menu_add)
            .setMessage(R.string.Congratulations)
            .setPositiveButton(R.string.ok, addOKInterface)
            .setNegativeButton(R.string.cancel, null)
            .show();
        }
    }

    public void notifyDataChanged(){
        mCur.requery();
        mAdapter.changeCursor(mCur);
        mAdapter.notifyDataSetChanged();
        refreshProgressBar();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        View v = inflater.inflate(R.layout.fragment_list, container, false);
        mLv = (ListView)v.findViewById(R.id.mylistview);

        mLv.setAdapter(mAdapter);

        mLv.setOnItemClickListener(new OnItemClickListener(){

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                ContentValues values = new ContentValues();
                CheckBox chb = (CheckBox)arg1.findViewById(R.id.lv_Checkbox);
                Long id = (Long)chb.getTag();

                values.put(MLConst.DBSTR_COL_CHECKBOX_STATE,
                        chb.isChecked()?MLConst.DB_STATE_UNCHECKED:MLConst.DB_STATE_CHECKED);
                
                mContext.getContentResolver().update(
                        mUri,
                        values,
                        MLConst.DBSTR_COL_ID + "=?",
                        new String[]{id.toString()});
            }
            
        });

        mLv.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v,
                    ContextMenuInfo menuInfo) {
                // TODO Auto-generated method stub
                //menu.add(Menu.NONE, DEL_ITEM, Menu.NONE, R.string.delete);
                getActivity().getMenuInflater().inflate(R.menu.listview_contextmenu, menu);
            }
        });
        mPB = (ProgressBar)v.findViewById(R.id.progressBar1);
        mTV = (TextView)v.findViewById(R.id.pbtv);
        refreshProgressBar();

        return v;
    }

    @Override
    public boolean onContextItemSelected(MenuItem item){
        switch(item.getItemId()){
        case R.id.del_item:{
            AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
            mContext.getContentResolver().delete(
                    mUri,
                    MLConst.DBSTR_COL_ID + "=" + Long.toString(info.id), null);
            break;
        }
        default:
            break;
        }
        return super.onContextItemSelected(item);
    }
}
